<template>
  <el-dialog
      v-model="visible"
      :title="isEdit ? '编辑任务' : '发布任务'"
      width="1000px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="任务标题" prop="name">
        <el-input v-model="form.name" placeholder="请输入任务标题"/>
      </el-form-item>

      <el-row>
        <el-col :span="12">
          <el-form-item label="任务类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择任务类型" style="width: 100%">
              <el-option :value="1" label="代购"/>
              <el-option :value="2" label="代取快递"/>
              <el-option :value="3" label="代办事务"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报酬金额" prop="reward">
            <el-input-number
                v-model="form.reward"
                :max="500"
                :min="1"
                :precision="2"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="任务描述" prop="description">
        <el-input
            v-model="form.description"
            :rows="3"
            placeholder="请详细描述任务内容"
            type="textarea"
        />
      </el-form-item>

      <el-form-item label="校区" prop="campus">
        <el-input v-model="form.campus" placeholder="请输入校区"/>
      </el-form-item>

      <el-row>
        <el-col :span="12">
          <el-form-item label="起点地址" prop="originAddress">
            <AMap v-model="form.originAddress" @change="location => {
              form.originAddress = location.address
              form.originLocation = {
                longitude: location.longitude,
                latitude: location.latitude
              }
            }"></AMap>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="终点地址" prop="destAddress">
            <AMap v-model="form.destAddress" @change="location => {
              form.destAddress = location.address
              form.destLocation = {
                longitude: location.longitude,
                latitude: location.latitude
              }
            }"></AMap>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="截止时间" prop="deadline">
            <el-date-picker
                v-model="form.deadline"
                placeholder="请选择截止时间"
                style="width: 100%"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预计时间" prop="estimatedTime">
            <el-input-number
                v-model="form.estimatedTime"
                :max="480"
                :min="5"
                style="width: 100%"
            />
            <span style="margin-left: 8px; color: #909399">分钟</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div style="text-align: center">
        <el-button :loading="submitting" type="primary" @click="handleSubmit">
          {{ isEdit ? '更新' : '发布' }}
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, reactive, ref, watch} from 'vue'
import request from '@/utils/request'
import AMap from "@/components/AMap.vue";

const props = defineProps({
  modelValue: Boolean,
  taskData: Object
})

const emit = defineEmits(['update:modelValue', 'published'])

const visible = ref(false)
const submitting = ref(false)
const formRef = ref()

const isEdit = computed(() => !!props.taskData?.id)

// 表单数据
const form = reactive({
  name: '',
  type: 1,
  description: '',
  reward: 10,
  campus: '',
  originAddress: '',
  destAddress: '',
  distance: 1,
  deadline: '',
  estimatedTime: 30
})

// 表单验证规则
const rules = {
  name: [{required: true, message: '请输入任务标题', trigger: 'blur'}],
  type: [{required: true, message: '请选择任务类型', trigger: 'change'}],
  description: [{required: false, message: '请输入任务描述', trigger: 'blur'}],
  reward: [{required: true, message: '请输入报酬金额', trigger: 'blur'}],
  campus: [{required: false, message: '请选择校区', trigger: 'change'}],
  originAddress: [{required: true, message: '请输入起点地址', trigger: 'blur'}],
  destAddress: [{required: true, message: '请输入终点地址', trigger: 'blur'}],
  distance: [{required: true, message: '请输入预计距离', trigger: 'blur'}],
  deadline: [{required: true, message: '请选择截止时间', trigger: 'change'}],
  estimatedTime: [{required: true, message: '请输入预计时间', trigger: 'blur'}]
}

// 监听显示状态
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val && props.taskData) {
    // 编辑模式，填充表单数据
    Object.assign(form, props.taskData)
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true

    if (isEdit.value) {
      await request.put('/task', {...form, id: props.taskData.id})
    } else {
      await request.post('/task', form)
    }

    emit('published')
    handleClose()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  formRef.value?.resetFields()
  Object.assign(form, {
    name: '',
    type: 1,
    description: '',
    reward: 10,
    campus: '',
    originAddress: '',
    destAddress: '',
    distance: 1,
    deadline: '',
    estimatedTime: 30
  })
}
</script>

<style scoped>
.el-button {
  width: 200px;
}
</style>
